package com.tanhua.commons.template;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.tanhua.commons.properties.AliyunOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
public class AliyunOssTemplate {
    @Autowired
    private AliyunOssProperties ossProperties;
    public String upload(InputStream is, String fileName) {
        // Endpoint地域节点，请按实际情况填写。
        String endpoint = ossProperties.getEndpoint();

        // 云账号AccessKey有所有API访问权限，
        String accessKeyId = ossProperties.getAccessKeyId();
        String accessKeySecret = ossProperties.getAccessKeySecret();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 上传路径配置，存储路径示例： 2021/01/14/mm.jpg
        String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + UUID.randomUUID().toString()
                + fileName.substring(fileName.lastIndexOf("."));
        //文件上传
        ossClient.putObject(ossProperties.getBucketName(), path, is);

        // 关闭OSSClient。
        ossClient.shutdown();

        log.info("上传文件到阿里云OSS：{}", ossProperties.getUrl() + "/" + path);
        return ossProperties.getUrl() + "/" + path;
    }


}
